package com.sun.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sun.constant.MessageConstant;
import com.sun.dto.UserLoginDTO;
import com.sun.entity.User;
import com.sun.exception.LoginFailedException;
import com.sun.mapper.UserMapper;
import com.sun.properties.WeChatProperties;
import com.sun.service.UserService;
import com.sun.utils.HttpClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.HttpClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;

@Service
@Slf4j
public class UserServiceImpl implements UserService {

    //微信服务接口: https://api.weixin.qq.com/sns/jscode2session
    public static final String WX_LOGIN = "https://api.weixin.qq.com/sns/jscode2session";

    @Autowired
    private WeChatProperties weChatProperties;

    @Autowired
    private UserMapper userMapper;
    /**
     * 微信登录
     * @param userLoginDTO
     * @return
     */
    @Override
    public User wxLogin(UserLoginDTO userLoginDTO) {
        //获取 小程序获取到的参数code -> 最终获取到openid
        String openid = getOpenid(userLoginDTO.getCode());

        //判断openid是否为空,如果为空则表示登陆失败,也就是业务异常
        if (openid == null){
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }

        //判断当前用户是否为新用户
        User user = userMapper.getByOpenid(openid);

        //如果是新用户,则完成自动注册->往数据库中存储新用户
        if(user == null){
            user = User.builder()
                    .openid(openid)
                    .createTime(LocalDateTime.now()).build();
            userMapper.insert(user);
        }

        return user;
    }

    /**
     * 调用微信服务接口, 获取微信用户的openid
     * @param code
     * @return
     */
    public String getOpenid(String code){
        //调用服务接口

        //web想要发送get/post请求到微信服务 -> HttpClien
        HashMap<String,String> map = new HashMap<>();
        map.put("appid",weChatProperties.getAppid());
        map.put("secret",weChatProperties.getSecret());
        map.put("js_code",code);
        map.put("grant_type","authorization_code");
        String json = HttpClientUtil.doGet(WX_LOGIN, map);

        JSONObject jsonObject = JSON.parseObject(json);
        String openid = jsonObject.getString("openid");
        return openid;
    }


}
